#!/usr/bin/env python

import sip
from voipy.utils import StringBuf as _p_strbuf

import methods
import codes

class StartLine(sip.SIP):
    sep = ' '
    def __init__(self, *args, **kwargs):
        self._line = []
        super(StartLine, self).__init__(*args, **kwargs)

    def _access(self, ndx, arg=None):
        if len(self._line) < ndx:
            pass # ERROR ... self._line.push(ndx, arg) ??
        if arg: self._line[ndx] = arg
        return self._line[ndx]

    def parse(self, line):
        self._line = line.split(self.sep, 3)

        if self._line[0].strip() == sip.SIPVERSION:
            self.__class__ = StatusLine().__class__
        else:
            self.__class__ = RequestLine().__class__

    def __str__(self):
        return self.sep.join(self._line)

class StatusLine(StartLine):
    def __init__(self, *args, **kwargs):
        """StatusLine([version, [code, [reason]]])
        """
        super(StatusLine, self).__init__(*args, **kwargs)

    def _version(self, arg=None):
        super(StatusLine, self)._access(0, arg)
    def _code(self, arg=None):
        super(StatusLine, self)._access(1, arg)
    def _reason(self, arg=None):
        super(StatusLine, self)._access(2, arg)

    version = property(lambda s: s._version(), lambda s,v: s._version(v))
    code = property(lambda s: s._code(), lambda s,v: s._code(v))
    reason = property(lambda s: s._reason(), lambda s,v: s._reason(v))

class RequestLine(StartLine):
    def __init__(self, *args, **kwargs):
        """RequestLine([method, [uri, [version]]])
        """
        super(RequestLine, self).__init__(*args, **kwargs)

    def _method(self, arg=None):
        super(RequestLine, self)._access(0, arg)
    def _uri(self, arg=None):
        super(RequestLine, self)._access(1, arg)
    def _version(self, arg=None):
        super(RequestLine, self)._access(2, arg)

    method = property(lambda s: s._method(), lambda s,v: s._method(v))
    uri = property(lambda s: s._uri(), lambda s,v: s._uri(v))
    version = property(lambda s: s._version(), lambda s,v: s._version(v))
